package Dao;

import entity.RolesBean;
import util.JDBCUtil;

import java.sql.SQLException;
import java.util.List;

public class RolesDao {
    private static RolesDao rolesDao;

    //查询所有
    public List<RolesBean> all() {
        List<RolesBean> list = null;
        String sql = "SELECT Rid,Rname,Rstate,Rdescribe FROM roles ORDER BY Rid";
        list = JDBCUtil.list(sql, RolesBean.class);
        return list;
    }

    //根据id获取权限
    public RolesBean one(int id) {
        RolesBean RolesBean = null;
        String sql = "SELECT Rid,Rname,Rstate,Rdescribe FROM roles WHERE Rid = ?";
        RolesBean = JDBCUtil.one(sql, RolesBean.class, id);
        return RolesBean;
    }

    //通过用户id获取该用户角色信息
    public RolesBean getRoleDataByUserId(int uid){
        RolesBean rolesBean = null;
        String sql = "SELECT Rid,Rname,Rstate,Rdescribe FROM roles,userList WHERE UroleId = Rid AND Uid=? ORDER BY Rid ";
        rolesBean = JDBCUtil.one(sql, RolesBean.class,uid);
        return rolesBean;
    }

    //添加新权限
    public int add(RolesBean rolesBean) {
        int num = 0;
        String sql = "insert into roles (Rid,Rname) values (?,?);";
        num = JDBCUtil.update(sql,rolesBean.getRid(), rolesBean.getRname());
        return num;
    }

    //根据id删除权限
    public int del(String rname) {
        int num = 0;
        String sql = "delete from roles where Rname = ?";
        num = JDBCUtil.update(sql, rname);
        return num;
    }
    //根据名字获取id
    public int getRoleIdByRoleName(String radioRolesCheckedName){
        int radioRolesCheckedId = 0;
        String sql = "SELECT Rid,Rname,Rstate,Rdescribe FROM roles WHERE Rname = ?";
        RolesBean rolesBean = JDBCUtil.one(sql, RolesBean.class, radioRolesCheckedName);
        radioRolesCheckedId = rolesBean.getRid();
        return radioRolesCheckedId;
    }


    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        RolesDao rolesBean = new RolesDao();
        List<RolesBean> all = rolesBean.all();
        for(RolesBean permissionBean:all){
            System.out.println(permissionBean.getRname());
        }
    }
}
